#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage " << argv[0] << " IP Port" << std::endl;
        exit(1);
    }
    // 2.解析参数
    char server_ip[17];
    memset((void *)server_ip, 0, sizeof(server_ip));
    memcpy((void *)server_ip, argv[1], strlen(argv[1]));
    uint16_t server_posr = std::stoi(argv[2]);
    // 3.创建socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(1);
    }
    std::cout << sockfd << std::endl;
    std::cout << server_posr << std::endl;
    std::cout << server_ip << std::endl;
    // 3.初始化struct sockaddr_in 结构体
    struct sockaddr_in s_server;
    // 清零
    memset((void *)&s_server, 0, sizeof(s_server));
    // bzero(&s_server, sizeof(s_server));
    //  IPv4
    s_server.sin_family = AF_INET;
    // 端口号
    //  本地格式->网络序列
    s_server.sin_port = htons(server_posr);
    // IP
    //  本地格式->网络序列
    //  1. IP转成4字节 2. 4字节转成网络序列 -> in_addr_t inet_addr(const char *cp);
    // local.sin_addr.s_addr = inet_addr(_ip.c_str()); // TODO
    s_server.sin_addr.s_addr = inet_addr(server_ip);
    // 结构体大小

    // 4.收发数据
    while (1)
    {
        // 5.获得输入信息
        std::string send_str;
        std::cout << "Please Enter-> ";
        std::getline(std::cin, send_str);
        // 6.发送
        ssize_t send_ret = sendto(sockfd, send_str.c_str(), send_str.size(), 0, (struct sockaddr *)&s_server, sizeof(s_server));
        if (send_ret == -1)
        {
            std::cout << "sendto error" << std::endl;
        }
        else
        {

            // 7.定义接收缓冲区
            char buffer[1024];
            memset((void *)buffer, 0, sizeof(buffer));
            struct sockaddr_in s_clinet;
            socklen_t l_clinet = sizeof(s_clinet);
            // 8.接收
            ssize_t receive_ret = recvfrom(sockfd, (void *)buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&s_clinet, &l_clinet);
            if (receive_ret > 0)
            {
                // 添加'\0'
                buffer[receive_ret] = 0;
                std::cout << "success: " << buffer << std::endl;
            }
        }
    }
    return 0;
}